/**
 * Created by Admin on 2018-05-12.
 */
(()=>{
	window.BlockModel = class BlockModel extends Model {
		static get table() {return 'block'};
		
		static get TYPE() {
			return {
				GROUP:'group',
				TEXT:'text',
				PASSWORD:'password',
				CODE:'code',
				TEMPLATE:'template',
				URL:'url',
			};
		};
		
		static typeText(type) {
			return {
				group:'组',
				text:'文本',
				password:'账号',
				code:'代码块',
				template:'模板',
				url:'超链接',
			}[type];
		}
		
		getLabel(value) { return this.get('label', value); }
		setLabel(value) { return this.set('label', value); }
		getType(value) { return this.get('type', value); }
		setType(value) { return this.set('type', value); }
		getValue(value) { return this.get('value', value); }
		setValue(value) { return this.set('value', value); }
		getPosition(value) { return this.get('position', value); }
		setPosition(value) { return this.set('position', value); }
		getParent(value) { return this.get('parent', value); }
		setParent(value) { return this.set('parent', value); }
		getOtherConfig(value) { return this.get('other_config', value); }
		setOtherConfig(value) { return this.set('other_config', value); }
		getPageId(value) { return this.get('page_id', value); }
		setPageId(value) { return this.set('page_id', value); }
		getComment(value) { return this.get('comment', value); }
		setComment(value) { return this.set('comment', value); }
		
		
		getChildBlocks() {
			if(this.getType() != this.constructor.TYPE.GROUP) {
				return [];
			}
			
			let collector = this.collector();
			collector.where('parent', this.getId())
				.where(COL('type').neq(this.constructor.TYPE.GROUP))
				.sort('position', 'ASC');
			
			return collector.load().get();
		}
		
		toString() {
			let text = '';
			
			if(this.getType() == this.constructor.TYPE.GROUP) {
				text += this.getLabel();
				text += "\n" + '-'.repeat(this.__getCharLength(this.getLabel('')));
			} else if(this.getType() == this.constructor.TYPE.PASSWORD) {
				text += '账号:' + this.getLabel() + ' 密码:' + this.getValue()
			} else {
				text += this.getLabel() + ':' + this.getValue()
			}
			
			if(this.getComment('').length > 0) {
				text += `  (${this.getComment('')})`;
			}
			
			text += "\n";
			
			let childs = this.getChildBlocks();
			
			for(let i=0; i<childs.length; i++) {
				text += childs[i].toString();
			}
			
			return text;
		}
		
		__getCharLength(str) {
			let len = 0;
			
			for(let i=0; i<str.length; i++) {
				if(str.charCodeAt(i) > 255) {
					len += 2;
				} else {
					len ++;
				}
			}
			
			return len;
		}
	};
	
	Core.setToParentWindow('BlockModel', BlockModel);
})();


